/*
 * Galaxium Messenger
 * 
 * Copyright (C) 2008 Paul Burton <paulburton89@gmail.com>
 * 
 * License: GNU General Public License (GPL)
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

using System;
using System.Globalization;
using System.Text;

using Anculus.Core;

namespace Galaxium.Protocol.Msn
{
	public class MsnOfflineTextMessage : MsnTextMessage
	{
		Guid _runID;
		int _seqNum;
		string _id;
		
		public new IEntity Source
		{
			get { return base.Source; }
			set { base.Source = value; }
		}
		
		public Guid RunID
		{
			get { return _runID; }
		}
		
		public int SequenceNum
		{
			get { return _seqNum; }
		}
		
		public string ID
		{
			get { return _id; }
			set { _id = value; }
		}
		
		public MsnOfflineTextMessage (IEntity source, DateTime timestamp, MsnTextStyle style, string message)
			: base (source, timestamp, style, message)
		{
			
		}
		
		public static MsnOfflineTextMessage FromMime (string str)
		{
			byte[] data = Encoding.UTF8.GetBytes (str);
			
			MIMECollection mime = new MIMECollection ();
			int mimeEnd = mime.Parse (data);
			
			byte[] msgData = new byte[data.Length - mimeEnd];
			Array.Copy (data, mimeEnd, msgData, 0, msgData.Length);
			
			string text = MsnEncodingUtility.Base64Decode (Encoding.UTF8.GetString (msgData));
			DateTime time = DateTime.ParseExact (mime["Date"], "d MMM yyyy HH:mm:ss zzz", CultureInfo.InvariantCulture);
			
			MsnOfflineTextMessage msg = new MsnOfflineTextMessage (null, time, new MsnTextStyle (), text);
			msg._runID = new Guid (mime["X-OIM-Run-Id"]);
			msg._seqNum = int.Parse (mime["X-OIM-Sequence-Num"]);
			
			return msg;
		}
	}
}
